<template>
  <div class="noteContent">
    <el-form ref="form" :model="note" label-width="80px">
      <el-form-item label="笔记标题">
        <el-input v-model="note.title" placeholder="今日笔记总结"></el-input>
      </el-form-item>
    </el-form>
    <mavon-editor
      v-model="note.md_text"
      @change="changeDate"
    />
    <el-button type="success" @click="save">保存</el-button>
  </div>
</template>

<script>
import { getNoteById, createNote, updateNote } from '@/api/note'
export default {
  name: 'NoteContent',
  data () {
    return {
      note: {
        title: '',
        md_text: '',
        html_text: ''
      }
    }
  },
  methods: {
    changeDate (mdText, htmlText) {
      this.note.md_text = mdText
      this.note.html_text = htmlText
    },
    async save () {
      if (this.id) {
        const { data: res } = await updateNote(this.id, this.note)
        if (res.code === 20000) {
          this.$message.success('修改成功')
          this.$router.push('/admin/note')
        } else {
          this.$message.error(res.error)
        }
      } else {
        const { data: res } = await createNote(this.note)
        if (res.code === 20000) {
          this.$router.push('/admin/note')
          this.$message.success('添加成功')
        } else {
          this.$message.error(res.error)
        }
      }
    }
  },
  computed: {
    id () {
      return this.$route.params.id
    }
  },
  async created () {
    if (this.id) {
      const { data: res } = await getNoteById(this.id)
      this.note = res.data.note
    }
  }
}
</script>
